package com.yiwu.common.component;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.CompletionSuggestOption;
import co.elastic.clients.elasticsearch.core.search.Suggestion;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import com.yiwu.common.config.ElasticConfig;
import jakarta.annotation.Resource;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.message.BasicHeader;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Component
public class ElasticComponent {

    @Autowired
    private ElasticConfig elasticConfig;

    /**
     * @param index 对应的索引文档
     * @param field 对应字段
     * @param prefix 查询参数
     * @return List<String>
     * @throws IOException
     */
    public List<String> getSuggestions(String index, String field,String prefix) throws IOException {
        ElasticsearchClient esClient = elasticConfig.getEsClient();

        SearchRequest request = SearchRequest.of(s -> s
                .index(index)  //查询对应的索引文档
                .suggest(su -> su
                        .suggesters("product-suggest", sug -> sug  //自定义的
                                .prefix(prefix) //keyword
                                .completion(c -> c
                                        .field(field)   //对应字段
                                        .skipDuplicates(true)  //去重
                                        .size(10)
                                )
                        )
                )
        );
        SearchResponse<? extends RequestOptions> response = esClient.search(request, RequestOptions.DEFAULT.getClass());

        //获取options
        List<? extends Suggestion<? extends RequestOptions>> suggestResult = response.suggest().get("product-suggest");

        return suggestResult.stream().flatMap(s -> s.completion().options().stream())
                .map(CompletionSuggestOption::text)
                .toList();
    }

}
